package com.fsnbigdata.web;

import com.fsnbigdata.domain.ZhEcologyNav;
import com.fsnbigdata.enums.ResultEnum;
import com.fsnbigdata.exception.ParamException;
import com.fsnbigdata.service.api.ZhEcologyNavService;
import com.fsnbigdata.util.ChineseInital;
import com.fsnbigdata.util.ReflectUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.lang.reflect.Method;
import java.security.Principal;
import java.util.List;
import java.util.Date;
import java.util.stream.Collectors;

/**
 * 旅游导航
 */
@RestController
@RequestMapping("/api/zhEcologyNav")
public class ZhEcologyNavController {
    @Autowired
    private ZhEcologyNavService zhEcologyNavService;

    /**
     * 查询所有
     * @return
     */
    @GetMapping(value = "list")
    public List<ZhEcologyNav> list(){
        return zhEcologyNavService.findAll();
    }

    /**
     * 模糊分页查询
     */
    @GetMapping("pageList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public Object pageList(HttpServletRequest request, Pageable pageable, Authentication authentication){
        class Ecotourism{
            Page<ZhEcologyNav> zhEcologyNavs;
            List<String> citys;
            Long[] types;

            public Page <ZhEcologyNav> getZhEcologyNavs() {
                return zhEcologyNavs;
            }

            public void setZhEcologyNavs(Page <ZhEcologyNav> zhEcologyNavs) {
                this.zhEcologyNavs = zhEcologyNavs;
            }

            public List <String> getCitys() {
                return citys;
            }

            public void setCitys(List <String> citys) {
                this.citys = citys;
            }

            public Long[] getTypes() {
                return types;
            }

            public void setTypes(Long[] types) {
                this.types = types;
            }
        }
        String city = request.getParameter( "city" );
        String type = request.getParameter( "type" );
        String condition = request.getParameter( "condition" );
        String creator=null;
        Page<ZhEcologyNav> zhEcologyNavs = zhEcologyNavService.pageList(city,type,condition,creator,pageable);
        List<String> citys = zhEcologyNavService.findAllCity();
        Long[] types = zhEcologyNavService.countType(city);
        Ecotourism ecotourism = new Ecotourism();
        ecotourism.setZhEcologyNavs( zhEcologyNavs );
        ecotourism.setCitys( citys );
        ecotourism.setTypes( types );
        return ecotourism;
    }

    @GetMapping("pageListByAdmin")
    @PreAuthorize("hasRole('DB_ZHECOLOGYNAV')")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", defaultValue = "0", dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "size", defaultValue = "20", dataType = "int", paramType = "query")
    })
    public Object pageListByAdmin(HttpServletRequest request, Pageable pageable, Authentication authentication){
        class Ecotourism{
            Page<ZhEcologyNav> zhEcologyNavs;
            List<String> citys;
            Long[] types;

            public Page <ZhEcologyNav> getZhEcologyNavs() {
                return zhEcologyNavs;
            }

            public void setZhEcologyNavs(Page <ZhEcologyNav> zhEcologyNavs) {
                this.zhEcologyNavs = zhEcologyNavs;
            }

            public List <String> getCitys() {
                return citys;
            }

            public void setCitys(List <String> citys) {
                this.citys = citys;
            }

            public Long[] getTypes() {
                return types;
            }

            public void setTypes(Long[] types) {
                this.types = types;
            }
        }
        String city = request.getParameter( "city" );
        String type = request.getParameter( "type" );
        String condition = request.getParameter( "condition" );
        List<String> authorities = authentication.getAuthorities().stream().map(it -> it.getAuthority()).collect(Collectors.toList());
        String creator=null;
        if(!authorities.contains("ROLE_USER_ADMIN")){
            creator = authentication.getName();
        }
        Page<ZhEcologyNav> zhEcologyNavs = zhEcologyNavService.pageList(city,type,condition,creator,pageable);
        List<String> citys = zhEcologyNavService.findAllCity();
        Long[] types = zhEcologyNavService.countType(city);
        Ecotourism ecotourism = new Ecotourism();
        ecotourism.setZhEcologyNavs( zhEcologyNavs );
        ecotourism.setCitys( citys );
        ecotourism.setTypes( types );
        return ecotourism;
    }

    /**
     * 根据字母索引查询
     * @param request
     * @return
     */
    @GetMapping(value = "queryByAlphabet")
    public List<ZhEcologyNav> queryByAlphabet(HttpServletRequest request){
        String alphabet = request.getParameter( "alphabet" );
        alphabet = alphabet.toLowerCase();
        return zhEcologyNavService.queryByAlphabet(alphabet==null||"".equals( alphabet )?"a":alphabet);
    }
    /**
     * 新增
     * @return
     */
    @PostMapping(value = "save")
    @PreAuthorize("hasRole('DB_ZHECOLOGYNAV')")
    @ApiOperation(value = "",notes = "save")
    public ZhEcologyNav save(@RequestBody @Valid ZhEcologyNav zhEcologyNav, BindingResult result, Principal principal) throws Exception {

        if (result.hasErrors()) {
            throw new ParamException(ResultEnum.PARAM_ERROR.getCode(),
                    result.getFieldError().getDefaultMessage());
        }
        zhEcologyNav.setInitial( ChineseInital.getFirstLetter( zhEcologyNav.getName().substring( 0,1 ) ) );
        zhEcologyNav.setId( null );
        zhEcologyNav.setAdd_time( new Date() );
        zhEcologyNav.setCreator(principal.getName());
        ZhEcologyNav newZhEcologyNav = zhEcologyNavService.save( zhEcologyNav );

        Class<?> clazz = ZhEcologyNavController.class;
        Method method = clazz.getMethod("save", ReflectUtil.getPeremeterClass(clazz, "save"));
        ReflectUtil.setAnnotationOn(method,"新增生态旅游导航，名称："+newZhEcologyNav.getName());

        return newZhEcologyNav;
    }

    /**
     * 修改
     * @param request
     * @return
     */
    @PostMapping("update")
    @PreAuthorize("hasRole('DB_ZHECOLOGYNAV')")
    @ApiOperation(value = "",notes = "update")
    public ZhEcologyNav update(HttpServletRequest request,@RequestBody @Valid ZhEcologyNav zhEcologyNav,BindingResult result,Principal principal) throws Exception {

        if (result.hasErrors()) {
            throw new ParamException(ResultEnum.PARAM_ERROR.getCode(),
                    result.getFieldError().getDefaultMessage());
        }
        ZhEcologyNav zhEcologyNav1 = zhEcologyNavService.findById( zhEcologyNav.getId() );
        zhEcologyNav.setInitial( ChineseInital.getFirstLetter( zhEcologyNav.getName().substring( 0,1 ) ) );

        String name=  zhEcologyNav1.getName();
        zhEcologyNav1.setName( zhEcologyNav.getName() );
        zhEcologyNav1.setName_en( zhEcologyNav.getName_en() );
        zhEcologyNav1.setCategory( zhEcologyNav.getCategory() );
        zhEcologyNav1.setProvince( zhEcologyNav.getProvince() );
        zhEcologyNav1.setCity( zhEcologyNav.getCity() );
        zhEcologyNav1.setCounty( zhEcologyNav.getCounty() );
        zhEcologyNav1.setAddress( zhEcologyNav.getAddress() );
        zhEcologyNav1.setContent( zhEcologyNav.getContent() );
        zhEcologyNav1.setInitial( zhEcologyNav.getInitial() );
        zhEcologyNav1.setImage( zhEcologyNav.getImage() );
        zhEcologyNav1.setCreator(principal.getName());
        ZhEcologyNav newZhEcologyNav = zhEcologyNavService.update( zhEcologyNav1 );

        Class<?> clazz = ZhEcologyNavController.class;
        Method method = clazz.getMethod("update", ReflectUtil.getPeremeterClass(clazz, "update"));
        ReflectUtil.setAnnotationOn(method,"更新生态旅游导航，名称："+name);

        return newZhEcologyNav;
    }

    /**
     * 查询一个，根据id
     * @param request
     * @return
     */
    @GetMapping("findOne")
    public ZhEcologyNav findById(HttpServletRequest request){
        Long id = Long.parseLong( request.getParameter( "id" ) );
        return zhEcologyNavService.findById( id );
    }

    /**
     * 删除一个，根据id
     * @param request
     * @return
     */
    @PostMapping("deleteOne")
    @PreAuthorize("hasRole('DB_ZHECOLOGYNAV')")
    @ApiOperation(value = "",notes = "delete")
    public Integer deleteOne(HttpServletRequest request) throws Exception {
        Long id = Long.parseLong( request.getParameter( "id" ) );
        String name = zhEcologyNavService.findById(id).getName();

        //返回 1 表示删除成功，返回 0 表示删除失败
        Integer code = zhEcologyNavService.deleteOne( id );
        Class<?> clazz = ZhEcologyNavController.class;
        Method method = clazz.getMethod("deleteOne", ReflectUtil.getPeremeterClass(clazz, "deleteOne"));
        ReflectUtil.setAnnotationOn(method,"删除生态旅游导航，名称："+name);

        return code;
    }

    /**
     * 删除多个，根据id，id之间是有“，”分隔
     * @param request
     * @return
     */
    @PostMapping("deleteMany")
    @PreAuthorize("hasRole('DB_ZHECOLOGYNAV')")
    public Integer deleteMany(HttpServletRequest request){
        //返回 1 表示删除成功，返回 0 表示删除失败
        return zhEcologyNavService.deleteMany( request.getParameter( "ids" ) );
    }
}
